package com.qunar.paydata.platform.controller.user;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.qunar.security.QSSO;
import com.qunar.security.qsso.model.QUser;
/**
 * 
 * @author leonyang.liu
 *
 * 用户服务控制器
 */
@Controller  
@RequestMapping("/iuser")
public class UserBaseController {  
   
	
	@RequestMapping("/hello")
	public String  hello(HttpServletRequest request,HttpServletResponse response) {
		//TODO  处理登陆校验相关逻辑
//		request.setAttribute("name", "admin");
		return "/hello";
	}
	@RequestMapping("/login/check")
	public String  check(HttpServletRequest request,HttpServletResponse response) {
		//TODO  处理登陆校验相关逻辑
		String username = request.getParameter("username");
		String password = request.getParameter("password");
			if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
				 return "redirect:/ "; 
			}
//		request.getSession().setAttribute("SESSION_NAME_LOGIN_RESULT", username);
//			ChannelProcessingFilter
//			FilterSecurityInterceptor
//		UsernamePasswordAuthenticationFilter
//		UsernamePasswordAuthenticationToken authenticationToken =
//                new UsernamePasswordAuthenticationToken(username, password);
//        Authentication authentication = this.authManager.authenticate(authenticationToken);
//        SecurityContextHolder.getContext().setAuthentication(authentication);


        /*
         * Reload user as password of authentication principal will be null after authorization and
         * password is needed for token generation
         */
//        	UserEntity user =  new UserEntity("admin", "admin");
        
//          Map<String, Object> map = new HashMap<String, Object>();
//          map.put("token", new TokenTransfer(TokenUtils.createToken(userDetails)));

//          return new TokenTransfer(TokenUtils.createToken(userDetails));
    		try {
			response.sendRedirect(request.getContextPath() + "/iuser/hello");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping("/login/q")
	public String qlogin(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		// TODO 从post数据里中获取到token参数
		String token = request.getParameter("token");
//		System.out.println(token);
		// 调用QSSO方法，获取QUser实例
		QUser user = QSSO.getQUser(token);
		if (null != user) {
			request.getSession().setAttribute("SESSION_NAME_LOGIN_RESULT", user);
		    // 登录成功, 从user中获取用户名， 可以使用userId来标识一个qunar员工，完成后面的登录逻辑（如：setSession或者setCookie）。
//		    System.out.println(user.getUserId() + user.getUserName() + user.getUniqueName());
			String userId = user.getUserId();
			map.put("name", userId);
			return "/hello";
		} else {
		    // 登录失败，token值非法或者过期了，（token只能verify一次，验证后就失效了）
			 return "redirect:/ "; 
		}
		
		
	}
	
	@RequestMapping("/login/loginout")
	public String loginout(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		request.getSession().invalidate();
		 return "redirect:/ "; 
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(@RequestParam(value = "logout", required = false) String logout) {

	  ModelAndView model = new ModelAndView();
//	  if (error != null) {
//	    model.addObject("error", "Invalid username and password!");
//	  }

	  if (logout != null) {
	    model.addObject("msg", "You've been logged out successfully.");
	  }
	  model.setViewName("login");

	  return model;
	}

	
}  